# -*- coding: utf-8 -*-
# Import Odoo models and fields
from odoo import models, fields, api, _


class SForecastBomStructureWizard(models.TransientModel):
    _name = 's.forecast.bom.structure.wizard'
    _description = 'Forecast BOM Structure Wizard'

    forecast_order_line_id = fields.Many2one(
        's.forecast.order.line',
        string='Forecast Line',
        readonly=True,
        required=True
    )
    product_id = fields.Many2one(
        'product.template',
        string='Product',
        related='forecast_order_line_id.engineering_confirmed_product_id',
        readonly=True,
        store=True
    )
    bom_id = fields.Many2one(
        'mrp.bom',
        string='Bill of Materials',
        compute='_compute_bom_id',
        readonly=True,
        store=True
    )
    bom_structure_line_ids = fields.One2many(
        's.forecast.bom.structure.line.wizard',
        'wizard_id',
        string='BOM Structure'
    )

    @api.depends('product_id')
    def _compute_bom_id(self):
        for rec in self:
            bom_by_product = self.env['mrp.bom']._bom_find(products=rec.product_id.product_variant_id)
            rec.bom_id = bom_by_product.get(rec.product_id.product_variant_id)

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        active_id = self._context.get('active_id')
        if active_id:
            forecast_line = self.env['s.forecast.order.line'].browse(active_id)
            if forecast_line.engineering_confirmed_product_id:
                product = forecast_line.engineering_confirmed_product_id.product_variant_id
                bom = self.env['mrp.bom']._bom_find(products=product)
                if bom:
                    bom_lines_data = self._get_bom_structure_recursive(bom, product, forecast_line.market_forecast_quantity, 1)
                    res['bom_structure_line_ids'] = bom_lines_data
                else:
                    # If no BOM, show the product itself as the top level
                    res['bom_structure_line_ids'] = [(0, 0, {
                        'product_id': product.product_tmpl_id.id,
                        'qty': forecast_line.market_forecast_quantity,
                        'uom_id': product.uom_id.id,
                        'level': 1,
                    })]
            res['forecast_order_line_id'] = active_id
        return res

    def _get_bom_structure_recursive(self, bom, product, qty, level):
        """
        Recursively processes BOM and sub-BOMs to build the structure for display.
        """
        structure_lines = []

        # Add the current product/component to the structure
        structure_lines.append((0, 0, {
            'product_id': product.product_tmpl_id.id,
            'qty': qty,
            'uom_id': product.uom_id.id,
            'level': level,
        }))

        for bom_line in bom[product].bom_line_ids:
            # Calculate quantity for the current BOM level
            line_qty = bom_line.product_qty * qty

            # If the component has its own BOM, recurse
            if bom_line.product_id.bom_ids:
                sub_bom = self.env['mrp.bom']._bom_find(products=bom_line.product_id)
                if sub_bom:
                    structure_lines.extend(self._get_bom_structure_recursive(sub_bom, bom_line.product_id, line_qty, level + 1))
            else:
                # If no sub-BOM, it's a raw material, add it directly
                structure_lines.append((0, 0, {
                    'product_id': bom_line.product_id.product_tmpl_id.id,
                    'qty': line_qty,
                    'uom_id': bom_line.product_uom_id.id,
                    'level': level + 1,
                }))
        return structure_lines
